
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
using ImgProcessing;
using Timing;
using NHibernateDB;
using FTPLib;

using DShowNET;
using DShowNET.Device;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;


namespace WebCam
{

    /// <summary> Summary description for MainForm. </summary>
    public class MainForm : System.Windows.Forms.Form, ISampleGrabberCB
    {
        //****************************************************************
        // Private constants
        //****************************************************************

        private const int WM_GRAPHNOTIFY  = 0x00008001; // message from graph

        private const int WS_CHILD        = 0x40000000; // attributes for video window
        private const int WS_CLIPCHILDREN = 0x02000000;
        private const int WS_CLIPSIBLINGS = 0x04000000;

        private readonly int ID_WEBCAM = 16;

        //****************************************************************
        // Private fields
        //****************************************************************

        private bool dontSaveNext = true, firstRun = true;
        private Int32 cPercent = 96, minSave = 96, count = 0, count2 = 0;
        private string saveTime = "";
        private Counter counter = new Counter();
        private float sec = 0;
        private Bitmap a;
        private Bitmap wanted;

        private bool                  firstActive;     // flag to detect first Form appearance
        private IBaseFilter           capFilter;       // base filter of the actually used video devices.
        private IGraphBuilder         graphBuilder;    // graph builder interface.
        private ICaptureGraphBuilder2 capGraph;        // capture graph builder interface.
        private ISampleGrabber        sampGrabber;
        private IMediaControl         mediaCtrl;       // control interface.
        private IMediaEventEx         mediaEvt;        // event interface.
        private IVideoWindow          videoWin;        // video window interface.
        private IBaseFilter           baseGrabFlt;     // grabber filter interface.
        private VideoInfoHeader       videoInfoHeader; // structure describing the bitmap to grab.
        private bool                  captured = true; // structure describing the bitmap to grab.
        private int                   bufferedSize;    // structure describing the bitmap to grab.
        private byte[]                savedArray;      // buffer for bitmap data.
        private ArrayList             capDevices;      // list of installed video devices.

#if DEBUG
        private int rotCookie = 0;
#endif

        private DateTime startDate;
        private DateTime stopDate;
        private string CNP = "";
        private string appPath = Application.StartupPath;
        private bool hasStarted = false;
        private string filePath;

        private string limba;
        private string FTPIp;
        private string FTPUser;
        private string FTPParola;
        private int FTPPort;
        private TcpClient tcpclnt = null;

        //****************************************************************
        // Interface fields
        //****************************************************************

        private System.Windows.Forms.Splitter splitter1;
        private System.Windows.Forms.ToolBar toolBar;
        private System.Windows.Forms.Panel videoPanel;
        private System.Windows.Forms.Panel stillPanel;
        private System.Windows.Forms.PictureBox pictureBox;
        private System.Windows.Forms.ToolBarButton toolBarBtnTune;
        private System.Windows.Forms.ToolBarButton toolBarBtnGrab;
        private System.Windows.Forms.ToolBarButton toolBarBtnSave;
        private System.Windows.Forms.ToolBarButton toolBarBtnSep;
        private System.Windows.Forms.ImageList imgListToolBar;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Label lblPercent;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.Label lblSavePercent;
        private System.Windows.Forms.Label lblSaveOrNot;
        private System.Windows.Forms.PictureBox pictureBox2;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.GroupBox groupBoxImageProcTime;
        private System.Windows.Forms.Label lbTimpTotal;
        private System.Windows.Forms.Label lblTotalTime;
        private System.Windows.Forms.Label lbTimp;
        private System.Windows.Forms.Label lblTime;
        private System.Windows.Forms.Label lblCount;
        private System.Windows.Forms.Button btnStop;
        private System.Windows.Forms.Label lblTimerValue;
        private System.Windows.Forms.TrackBar trckBarTimer;
        private System.Windows.Forms.TrackBar trckBarSaveValue;
        private GroupBox gbDatePacient;
        private Label lbCNPPacient;
        private Button btSelectarePacient;
        private Label lbCNP;
        private Button btSalvare;
        private CheckBox cbTrimiteAlerte;
        private System.ComponentModel.IContainer components;


        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            XMLParser parser = new XMLParser(@"C:\Configurare.xml");
            Dictionary<string, string> config =
                parser.ExtractAttributePairs("Configurare",
                                             string.Empty,
                                             string.Empty,
                                             "name",
                                             "formula");

            Application.Run(new MainForm(config["Limba"],
                                         config["FTPIp"],
                                         config["FTPUser"],
                                         config["FTPParola"],
                                         config["FTPPort"]));
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public MainForm(string limba,
                        string FTPIp,
                        string FTPUser,
                        string FTPParola,
                        string FTPPort)
        {
            // Required for Windows Form Designer support
            InitializeComponent();
            Rename(limba);

            this.limba = limba;
            this.FTPIp = FTPIp;
            this.FTPParola = FTPParola;
            this.FTPPort = Int32.Parse(FTPPort);
            this.FTPUser = FTPUser;

            trckBarSaveValue.Value = cPercent;
            lblSavePercent.Text = cPercent + "%";

            timer1.Interval = trckBarTimer.Value;
            lblTimerValue.Text = trckBarTimer.Value.ToString();
            System.Windows.Forms.ToolBarButtonClickEventArgs ee = new ToolBarButtonClickEventArgs(toolBarBtnGrab);
            toolBar_ButtonClick(toolBarBtnGrab, ee);
        }

        private static List<Control> GetControls(Control form)
        {
            var controlList = new List<Control>();

            foreach (Control childControl in form.Controls)
            {
                controlList.AddRange(GetControls(childControl));
                controlList.Add(childControl);
            }
            return controlList;
        }

        private void Rename(string limba)
        {
            List<Control> controlsList = new List<Control>();
            controlsList = GetControls(this);

            string xmlFile = @"C:\Language" + limba + ".xml";
            XMLParser xmlParser = new XMLParser(xmlFile);
            Dictionary<string, string> namesForm = xmlParser.ExtractAttributePairs(this.Name, string.Empty, string.Empty, "name", "formula");

            foreach (Control c in controlsList)
            {
                if (namesForm.ContainsKey(c.Name))
                    c.Text = namesForm[c.Name];
            }
        }

        /// <summary> Clean up any resources being used. </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                CloseInterfaces();

                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.toolBar = new System.Windows.Forms.ToolBar();
            this.toolBarBtnTune = new System.Windows.Forms.ToolBarButton();
            this.toolBarBtnGrab = new System.Windows.Forms.ToolBarButton();
            this.toolBarBtnSep = new System.Windows.Forms.ToolBarButton();
            this.toolBarBtnSave = new System.Windows.Forms.ToolBarButton();
            this.imgListToolBar = new System.Windows.Forms.ImageList(this.components);
            this.videoPanel = new System.Windows.Forms.Panel();
            this.splitter1 = new System.Windows.Forms.Splitter();
            this.stillPanel = new System.Windows.Forms.Panel();
            this.lblTimerValue = new System.Windows.Forms.Label();
            this.trckBarTimer = new System.Windows.Forms.TrackBar();
            this.btnStop = new System.Windows.Forms.Button();
            this.btnStart = new System.Windows.Forms.Button();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            this.lblSaveOrNot = new System.Windows.Forms.Label();
            this.lblSavePercent = new System.Windows.Forms.Label();
            this.trckBarSaveValue = new System.Windows.Forms.TrackBar();
            this.lblPercent = new System.Windows.Forms.Label();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.pictureBox = new System.Windows.Forms.PictureBox();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.groupBoxImageProcTime = new System.Windows.Forms.GroupBox();
            this.lbTimpTotal = new System.Windows.Forms.Label();
            this.lblTotalTime = new System.Windows.Forms.Label();
            this.lbTimp = new System.Windows.Forms.Label();
            this.lblTime = new System.Windows.Forms.Label();
            this.lblCount = new System.Windows.Forms.Label();
            this.gbDatePacient = new System.Windows.Forms.GroupBox();
            this.btSalvare = new System.Windows.Forms.Button();
            this.lbCNP = new System.Windows.Forms.Label();
            this.lbCNPPacient = new System.Windows.Forms.Label();
            this.btSelectarePacient = new System.Windows.Forms.Button();
            this.cbTrimiteAlerte = new System.Windows.Forms.CheckBox();
            this.stillPanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trckBarTimer)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trckBarSaveValue)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
            this.groupBoxImageProcTime.SuspendLayout();
            this.gbDatePacient.SuspendLayout();
            this.SuspendLayout();
            // 
            // toolBar
            // 
            this.toolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
            this.toolBarBtnTune,
            this.toolBarBtnGrab,
            this.toolBarBtnSep,
            this.toolBarBtnSave});
            this.toolBar.Cursor = System.Windows.Forms.Cursors.Hand;
            this.toolBar.DropDownArrows = true;
            this.toolBar.Enabled = false;
            this.toolBar.ImageList = this.imgListToolBar;
            this.toolBar.Location = new System.Drawing.Point(0, 0);
            this.toolBar.Name = "toolBar";
            this.toolBar.ShowToolTips = true;
            this.toolBar.Size = new System.Drawing.Size(774, 42);
            this.toolBar.TabIndex = 0;
            this.toolBar.Visible = false;
            this.toolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar_ButtonClick);
            // 
            // toolBarBtnTune
            // 
            this.toolBarBtnTune.Enabled = false;
            this.toolBarBtnTune.ImageIndex = 0;
            this.toolBarBtnTune.Name = "toolBarBtnTune";
            this.toolBarBtnTune.Text = "Tune";
            this.toolBarBtnTune.ToolTipText = "TV tuner dialog";
            // 
            // toolBarBtnGrab
            // 
            this.toolBarBtnGrab.ImageIndex = 1;
            this.toolBarBtnGrab.Name = "toolBarBtnGrab";
            this.toolBarBtnGrab.Text = "Grab";
            this.toolBarBtnGrab.ToolTipText = "Grab picture from stream";
            // 
            // toolBarBtnSep
            // 
            this.toolBarBtnSep.Enabled = false;
            this.toolBarBtnSep.Name = "toolBarBtnSep";
            this.toolBarBtnSep.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
            // 
            // toolBarBtnSave
            // 
            this.toolBarBtnSave.Enabled = false;
            this.toolBarBtnSave.ImageIndex = 2;
            this.toolBarBtnSave.Name = "toolBarBtnSave";
            this.toolBarBtnSave.Text = "Save";
            this.toolBarBtnSave.ToolTipText = "Save image to file";
            // 
            // imgListToolBar
            // 
            this.imgListToolBar.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgListToolBar.ImageStream")));
            this.imgListToolBar.TransparentColor = System.Drawing.Color.Transparent;
            this.imgListToolBar.Images.SetKeyName(0, "");
            this.imgListToolBar.Images.SetKeyName(1, "");
            this.imgListToolBar.Images.SetKeyName(2, "");
            // 
            // videoPanel
            // 
            this.videoPanel.BackColor = System.Drawing.Color.Black;
            this.videoPanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.videoPanel.Location = new System.Drawing.Point(8, 40);
            this.videoPanel.Name = "videoPanel";
            this.videoPanel.Size = new System.Drawing.Size(296, 304);
            this.videoPanel.TabIndex = 1;
            this.videoPanel.Resize += new System.EventHandler(this.videoPanel_Resize);
            // 
            // splitter1
            // 
            this.splitter1.Location = new System.Drawing.Point(0, 42);
            this.splitter1.Name = "splitter1";
            this.splitter1.Size = new System.Drawing.Size(5, 437);
            this.splitter1.TabIndex = 2;
            this.splitter1.TabStop = false;
            // 
            // stillPanel
            // 
            this.stillPanel.AutoScroll = true;
            this.stillPanel.AutoScrollMargin = new System.Drawing.Size(8, 8);
            this.stillPanel.AutoScrollMinSize = new System.Drawing.Size(32, 32);
            this.stillPanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.stillPanel.Controls.Add(this.lblTimerValue);
            this.stillPanel.Controls.Add(this.trckBarTimer);
            this.stillPanel.Controls.Add(this.btnStop);
            this.stillPanel.Controls.Add(this.btnStart);
            this.stillPanel.Controls.Add(this.pictureBox2);
            this.stillPanel.Controls.Add(this.lblSaveOrNot);
            this.stillPanel.Controls.Add(this.lblSavePercent);
            this.stillPanel.Controls.Add(this.trckBarSaveValue);
            this.stillPanel.Controls.Add(this.lblPercent);
            this.stillPanel.Controls.Add(this.pictureBox1);
            this.stillPanel.Controls.Add(this.pictureBox);
            this.stillPanel.Location = new System.Drawing.Point(312, 40);
            this.stillPanel.Name = "stillPanel";
            this.stillPanel.Size = new System.Drawing.Size(459, 302);
            this.stillPanel.TabIndex = 3;
            // 
            // lblTimerValue
            // 
            this.lblTimerValue.Location = new System.Drawing.Point(397, 16);
            this.lblTimerValue.Name = "lblTimerValue";
            this.lblTimerValue.Size = new System.Drawing.Size(48, 24);
            this.lblTimerValue.TabIndex = 10;
            this.lblTimerValue.Text = "400";
            this.lblTimerValue.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // trckBarTimer
            // 
            this.trckBarTimer.LargeChange = 300;
            this.trckBarTimer.Location = new System.Drawing.Point(400, 48);
            this.trckBarTimer.Maximum = 1000;
            this.trckBarTimer.Minimum = 7;
            this.trckBarTimer.Name = "trckBarTimer";
            this.trckBarTimer.Orientation = System.Windows.Forms.Orientation.Vertical;
            this.trckBarTimer.Size = new System.Drawing.Size(42, 240);
            this.trckBarTimer.SmallChange = 10;
            this.trckBarTimer.TabIndex = 9;
            this.trckBarTimer.Value = 400;
            this.trckBarTimer.ValueChanged += new System.EventHandler(this.trckBarTimer_ValueChanged);
            // 
            // btnStop
            // 
            this.btnStop.Enabled = false;
            this.btnStop.Location = new System.Drawing.Point(249, 240);
            this.btnStop.Name = "btnStop";
            this.btnStop.Size = new System.Drawing.Size(87, 40);
            this.btnStop.TabIndex = 8;
            this.btnStop.Text = "[Stop]";
            this.btnStop.UseVisualStyleBackColor = true;
            this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(249, 16);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(87, 40);
            this.btnStart.TabIndex = 7;
            this.btnStart.Text = "[Start]";
            this.btnStart.UseVisualStyleBackColor = true;
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            // 
            // pictureBox2
            // 
            this.pictureBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.pictureBox2.Location = new System.Drawing.Point(3, 192);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(240, 88);
            this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox2.TabIndex = 6;
            this.pictureBox2.TabStop = false;
            // 
            // lblSaveOrNot
            // 
            this.lblSaveOrNot.Location = new System.Drawing.Point(249, 192);
            this.lblSaveOrNot.Name = "lblSaveOrNot";
            this.lblSaveOrNot.Size = new System.Drawing.Size(87, 45);
            this.lblSaveOrNot.TabIndex = 5;
            this.lblSaveOrNot.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // lblSavePercent
            // 
            this.lblSavePercent.Location = new System.Drawing.Point(341, 16);
            this.lblSavePercent.Name = "lblSavePercent";
            this.lblSavePercent.Size = new System.Drawing.Size(48, 24);
            this.lblSavePercent.TabIndex = 4;
            this.lblSavePercent.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // trckBarSaveValue
            // 
            this.trckBarSaveValue.Enabled = false;
            this.trckBarSaveValue.Location = new System.Drawing.Point(344, 48);
            this.trckBarSaveValue.Maximum = 100;
            this.trckBarSaveValue.Name = "trckBarSaveValue";
            this.trckBarSaveValue.Orientation = System.Windows.Forms.Orientation.Vertical;
            this.trckBarSaveValue.Size = new System.Drawing.Size(42, 240);
            this.trckBarSaveValue.TabIndex = 3;
            this.trckBarSaveValue.ValueChanged += new System.EventHandler(this.trckBarSaveValue_ValueChanged);
            // 
            // lblPercent
            // 
            this.lblPercent.Location = new System.Drawing.Point(296, 132);
            this.lblPercent.Name = "lblPercent";
            this.lblPercent.Size = new System.Drawing.Size(40, 32);
            this.lblPercent.TabIndex = 2;
            this.lblPercent.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // pictureBox1
            // 
            this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.pictureBox1.Location = new System.Drawing.Point(3, 104);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(240, 88);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox1.TabIndex = 1;
            this.pictureBox1.TabStop = false;
            // 
            // pictureBox
            // 
            this.pictureBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.pictureBox.Location = new System.Drawing.Point(3, 16);
            this.pictureBox.Name = "pictureBox";
            this.pictureBox.Size = new System.Drawing.Size(240, 88);
            this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox.TabIndex = 0;
            this.pictureBox.TabStop = false;
            // 
            // timer1
            // 
            this.timer1.Interval = 600;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // groupBoxImageProcTime
            // 
            this.groupBoxImageProcTime.Controls.Add(this.lbTimpTotal);
            this.groupBoxImageProcTime.Controls.Add(this.lblTotalTime);
            this.groupBoxImageProcTime.Controls.Add(this.lbTimp);
            this.groupBoxImageProcTime.Controls.Add(this.lblTime);
            this.groupBoxImageProcTime.ForeColor = System.Drawing.SystemColors.ControlText;
            this.groupBoxImageProcTime.Location = new System.Drawing.Point(8, 344);
            this.groupBoxImageProcTime.Name = "groupBoxImageProcTime";
            this.groupBoxImageProcTime.Size = new System.Drawing.Size(536, 56);
            this.groupBoxImageProcTime.TabIndex = 17;
            this.groupBoxImageProcTime.TabStop = false;
            this.groupBoxImageProcTime.Text = "[Timpul de procesare a imagini]";
            // 
            // lbTimpTotal
            // 
            this.lbTimpTotal.ForeColor = System.Drawing.SystemColors.ControlText;
            this.lbTimpTotal.Location = new System.Drawing.Point(200, 24);
            this.lbTimpTotal.Name = "lbTimpTotal";
            this.lbTimpTotal.Size = new System.Drawing.Size(64, 24);
            this.lbTimpTotal.TabIndex = 19;
            this.lbTimpTotal.Text = "[Timp total]";
            this.lbTimpTotal.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.lbTimpTotal.UseMnemonic = false;
            // 
            // lblTotalTime
            // 
            this.lblTotalTime.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.lblTotalTime.ForeColor = System.Drawing.Color.DarkRed;
            this.lblTotalTime.Location = new System.Drawing.Point(272, 24);
            this.lblTotalTime.Name = "lblTotalTime";
            this.lblTotalTime.Size = new System.Drawing.Size(240, 24);
            this.lblTotalTime.TabIndex = 18;
            this.lblTotalTime.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.lblTotalTime.UseMnemonic = false;
            // 
            // lbTimp
            // 
            this.lbTimp.ForeColor = System.Drawing.SystemColors.ControlText;
            this.lbTimp.Location = new System.Drawing.Point(8, 24);
            this.lbTimp.Name = "lbTimp";
            this.lbTimp.Size = new System.Drawing.Size(44, 24);
            this.lbTimp.TabIndex = 17;
            this.lbTimp.Text = "[Timp]";
            this.lbTimp.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.lbTimp.UseMnemonic = false;
            // 
            // lblTime
            // 
            this.lblTime.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.lblTime.ForeColor = System.Drawing.Color.DarkRed;
            this.lblTime.Location = new System.Drawing.Point(58, 24);
            this.lblTime.Name = "lblTime";
            this.lblTime.Size = new System.Drawing.Size(136, 24);
            this.lblTime.TabIndex = 16;
            this.lblTime.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.lblTime.UseMnemonic = false;
            // 
            // lblCount
            // 
            this.lblCount.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.lblCount.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(178)), true);
            this.lblCount.ForeColor = System.Drawing.Color.DarkRed;
            this.lblCount.Location = new System.Drawing.Point(623, 355);
            this.lblCount.Name = "lblCount";
            this.lblCount.Size = new System.Drawing.Size(80, 16);
            this.lblCount.TabIndex = 18;
            this.lblCount.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.lblCount.UseMnemonic = false;
            // 
            // gbDatePacient
            // 
            this.gbDatePacient.Controls.Add(this.btSalvare);
            this.gbDatePacient.Controls.Add(this.lbCNP);
            this.gbDatePacient.Controls.Add(this.lbCNPPacient);
            this.gbDatePacient.Controls.Add(this.btSelectarePacient);
            this.gbDatePacient.ForeColor = System.Drawing.SystemColors.ControlText;
            this.gbDatePacient.Location = new System.Drawing.Point(8, 406);
            this.gbDatePacient.Name = "gbDatePacient";
            this.gbDatePacient.Size = new System.Drawing.Size(763, 67);
            this.gbDatePacient.TabIndex = 19;
            this.gbDatePacient.TabStop = false;
            this.gbDatePacient.Text = "[Date Pacient]";
            // 
            // btSalvare
            // 
            this.btSalvare.Location = new System.Drawing.Point(437, 22);
            this.btSalvare.Name = "btSalvare";
            this.btSalvare.Size = new System.Drawing.Size(75, 23);
            this.btSalvare.TabIndex = 3;
            this.btSalvare.Text = "[Salvare]";
            this.btSalvare.UseVisualStyleBackColor = true;
            this.btSalvare.Click += new System.EventHandler(this.btSalvare_Click);
            // 
            // lbCNP
            // 
            this.lbCNP.AutoSize = true;
            this.lbCNP.Location = new System.Drawing.Point(91, 27);
            this.lbCNP.Name = "lbCNP";
            this.lbCNP.Size = new System.Drawing.Size(116, 13);
            this.lbCNP.TabIndex = 2;
            this.lbCNP.Text = "[nici un pacient selctat]";
            // 
            // lbCNPPacient
            // 
            this.lbCNPPacient.AutoSize = true;
            this.lbCNPPacient.Location = new System.Drawing.Point(8, 27);
            this.lbCNPPacient.Name = "lbCNPPacient";
            this.lbCNPPacient.Size = new System.Drawing.Size(77, 13);
            this.lbCNPPacient.TabIndex = 1;
            this.lbCNPPacient.Text = "[CNP Pacient:]";
            // 
            // btSelectarePacient
            // 
            this.btSelectarePacient.Location = new System.Drawing.Point(248, 22);
            this.btSelectarePacient.Name = "btSelectarePacient";
            this.btSelectarePacient.Size = new System.Drawing.Size(145, 23);
            this.btSelectarePacient.TabIndex = 0;
            this.btSelectarePacient.Text = "[Selectare Pacient]";
            this.btSelectarePacient.UseVisualStyleBackColor = true;
            this.btSelectarePacient.Click += new System.EventHandler(this.btSelectarePacient_Click);
            // 
            // cbTrimiteAlerte
            // 
            this.cbTrimiteAlerte.AutoSize = true;
            this.cbTrimiteAlerte.Location = new System.Drawing.Point(563, 383);
            this.cbTrimiteAlerte.Name = "cbTrimiteAlerte";
            this.cbTrimiteAlerte.Size = new System.Drawing.Size(190, 17);
            this.cbTrimiteAlerte.TabIndex = 20;
            this.cbTrimiteAlerte.Text = "[Trimite alerte la detectare miscare]";
            this.cbTrimiteAlerte.UseVisualStyleBackColor = true;
            // 
            // MainForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(774, 479);
            this.Controls.Add(this.cbTrimiteAlerte);
            this.Controls.Add(this.gbDatePacient);
            this.Controls.Add(this.lblCount);
            this.Controls.Add(this.groupBoxImageProcTime);
            this.Controls.Add(this.stillPanel);
            this.Controls.Add(this.splitter1);
            this.Controls.Add(this.videoPanel);
            this.Controls.Add(this.toolBar);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "MainForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "WebCamMed";
            this.Activated += new System.EventHandler(this.MainForm_Activated);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
            this.stillPanel.ResumeLayout(false);
            this.stillPanel.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.trckBarTimer)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trckBarSaveValue)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
            this.groupBoxImageProcTime.ResumeLayout(false);
            this.gbDatePacient.ResumeLayout(false);
            this.gbDatePacient.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

        private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Hide();
            CloseInterfaces();
        }

        /// <summary> detect first form appearance, start grabber. </summary>
        private void MainForm_Activated(object sender, System.EventArgs e)
        {
            if (firstActive)
                return;
            firstActive = true;

            if (!DsUtils.IsCorrectDirectXVersion())
            {
                MessageBox.Show(this, "DirectX 8.1 NOT installed!", "DirectShow.NET", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                this.Close(); return;
            }

            if (!DsDev.GetDevicesOfCat(FilterCategory.VideoInputDevice, out capDevices))
            {
                MessageBox.Show(this, "No video capture devices found!", "DirectShow.NET", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                this.Close(); return;
            }

            DsDevice dev = null;
            if (capDevices.Count == 1)
                dev = capDevices[0] as DsDevice;
            else
            {
                DeviceSelector selector = new DeviceSelector(capDevices);
                selector.ShowDialog(this);
                dev = selector.SelectedDevice;
            }

            if (dev == null)
            {
                this.Close(); return;
            }

            if (!StartupVideo(dev.Mon))
                this.Close();
        }

        private void videoPanel_Resize(object sender, System.EventArgs e)
        {
            ResizeVideoWindow();
        }

        /// <summary> handler for toolbar button clicks. </summary>
        private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
        {
            Trace.WriteLine("!!BTN: toolBar_ButtonClick");

            int hr;
            if (sampGrabber == null)
                return;

            if (e.Button == toolBarBtnGrab)
            {
                Trace.WriteLine("!!BTN: toolBarBtnGrab");

                if (savedArray == null)
                {
                    int size = videoInfoHeader.BmiHeader.ImageSize;
                    if ((size < 1000) || (size > 16000000))
                        return;
                    savedArray = new byte[size + 64000];
                }

                toolBarBtnSave.Enabled = false;
                Image old = pictureBox.Image;
                pictureBox.Image = null;
                if (old != null)
                    old.Dispose();

                toolBarBtnGrab.Enabled = false;
                captured = false;
                hr = sampGrabber.SetCallback(this, 1);
            }
            else if (e.Button == toolBarBtnSave)
            {
                Trace.WriteLine("!!BTN: toolBarBtnSave");

                SaveFileDialog sd = new SaveFileDialog();
                sd.FileName = @"DsNET.bmp";
                sd.Title = "Save Image as...";
                sd.Filter = "Bitmap file (*.bmp)|*.bmp";
                sd.FilterIndex = 1;
                if (sd.ShowDialog() != DialogResult.OK)
                    return;

                pictureBox.Image.Save(sd.FileName, ImageFormat.Bmp);		// save to new bmp file
            }
            else if (e.Button == toolBarBtnTune)
            {
                if (capGraph != null)
                    DsUtils.ShowTunerPinDialog(capGraph, capFilter, this.Handle);
            }

        }

        private void SendAlertMessage(string Msg)
        {
            if (cbTrimiteAlerte.Checked == false)
                return;

            int j = 0;

            if (tcpclnt == null)
                tcpclnt = new TcpClient();

            try
            {
                // Connect to server
                if (!tcpclnt.Connected)
                    tcpclnt.Connect("127.0.0.1", 8080);

                //
                // Send the alert
                //

                ASCIIEncoding asen = new ASCIIEncoding();

                Stream stm = tcpclnt.GetStream();
                byte[] buff = new byte[4096], tmp;
                int msgLen, cnpLen;

                // lungime
                msgLen = asen.GetBytes(Msg).Length;
                cnpLen = asen.GetBytes(CNP).Length;

                tmp = BitConverter.GetBytes(msgLen + cnpLen + 4);
                for (int i = 0; i < 4; i++, j++)
                    buff[j] = tmp[i];

                // ID WebCam
                tmp = BitConverter.GetBytes(ID_WEBCAM);
                for (int i = 0; i < 4; i++, j++)
                    buff[j] = tmp[i];

                // CNP
                tmp = asen.GetBytes(CNP);
                for (int i = 0; i < cnpLen; i++, j++)
                    buff[j] = tmp[i];

                // ID WebCam
                tmp = BitConverter.GetBytes(ID_WEBCAM);
                for (int i = 0; i < 4; i++, j++)
                    buff[j] = tmp[i];

                // Msg
                tmp = asen.GetBytes(Msg);
                for (int i = 0; i < msgLen; i++, j++)
                    buff[j] = tmp[i];

                // transmitere
                stm.Write(buff, 0, j);
            }
            catch
            {
                tcpclnt.Close();
                tcpclnt = null;
            }

        } /* SendAlertMessage */

        /// <summary> capture event, triggered by buffer callback. </summary>
        void OnCaptureDone()
        {
            Trace.WriteLine("!!DLG: OnCaptureDone");

            try
            {
                filePath = CNP + " from date " + startDate.ToString() + "\\";
                filePath = filePath.Replace('/', '.');
                filePath = filePath.Replace(':', '.');

                toolBarBtnGrab.Enabled = true;
                int hr;
                if (sampGrabber == null)
                    return;
                hr = sampGrabber.SetCallback(null, 0);

                int w = videoInfoHeader.BmiHeader.Width;
                int h = videoInfoHeader.BmiHeader.Height;
                if (((w & 0x03) != 0) || (w < 32) || (w > 4096) || (h < 32) || (h > 4096))
                    return;
                //get Image
                int stride = w * 3;
                GCHandle handle = GCHandle.Alloc(savedArray, GCHandleType.Pinned);
                int scan0 = (int)handle.AddrOfPinnedObject();
                scan0 += (h - 1) * stride;
                Bitmap b = new Bitmap(w, h, -stride, PixelFormat.Format24bppRgb, (IntPtr)scan0);
                handle.Free();


                pictureBox1.Image = b;
                b = new Bitmap(pictureBox1.Image);

                if (firstRun)
                {
                    firstRun = false;
                    pictureBox.Image = b;
                    a = new Bitmap(b);

                    if (!System.IO.Directory.Exists(filePath))
                    {
                        System.IO.Directory.CreateDirectory(filePath);
                    }
                }
                else
                {
                    count++;
                    wanted = new Bitmap(b.Width, b.Height);
                    Int32 percent;
                    counter.Start();
                    ImageProcessing imageProcessing = new ImageProcessing(a, b, wanted);
                    imageProcessing.CompareUnsafeFaster(out percent);
                    percent = (Int32)(percent * 100 / (b.Width * b.Height));
                    counter.Stop();
                    pictureBox2.Image = wanted;
                    if ((percent >= cPercent) && !dontSaveNext)
                    {
                        //imageProcessing.Save(Application.StartupPath + "\\wanted\\Wanted" + count + "-" + percent + "-" + System.DateTime.Now.Millisecond.ToString() + ".jpg");
                        //saveTime = count + "-" + percent + "-" + System.DateTime.Now.Millisecond.ToString() + ".jpg";
                        saveTime = CNP + " - " +
                                   DateTime.Now.ToString() + " " + DateTime.Now.Millisecond.ToString();
                        //b.Save(Application.StartupPath + "\\Wanted\\first" + saveTime, System.Drawing.Imaging.ImageFormat.Jpeg);
                        //a.Save(Application.StartupPath + "\\Wanted\\second" + saveTime, System.Drawing.Imaging.ImageFormat.Jpeg);
                        filePath = filePath + saveTime;
                        filePath = filePath.Replace('/', '.');
                        filePath = filePath.Replace(':', '.');
                        a.Save(filePath + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        count2++;
                        Console.Beep();
                        dontSaveNext = true;
                        lblSaveOrNot.Text = "don'tSaveNext";
                        SendAlertMessage("Miscare detectata!");

                    }
                    else
                    {
                        dontSaveNext = false;
                        lblSaveOrNot.Text = "SaveNext";
                    }
                    this.lblTime.Text = counter.ToString();
                    sec += counter.Seconds;
                    lblTotalTime.Text = sec.ToString() + " Seconds.";
                    counter.Clear();

                    lblCount.Text = count2 + "/" + count;
                    lblPercent.Text = percent + "%";

                    //the below code compute the minimum save percent
                    //because the defference between webcams,
                    //daylight

                    if ((percent - minSave) > 5)
                    {
                        try
                        {
                            trckBarSaveValue.Value = percent + 5;
                            minSave = percent;
                        }
                        catch { }
                    }

                    //else if(percent<minSave)
                    try
                    {
                        minSave = (minSave + percent) / 2;
                        trckBarSaveValue.Value = minSave + 5;
                    }
                    catch { }


                }

                pictureBox.Image = b;
                a = new Bitmap(pictureBox.Image);

                savedArray = null;

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        /// <summary> start all the interfaces, graphs and preview window. </summary>
        bool StartupVideo(UCOMIMoniker mon)
        {
            int hr;
            try
            {
                if (!CreateCaptureDevice(mon))
                    return false;

                if (!GetInterfaces())
                    return false;

                if (!SetupGraph())
                    return false;

                if (!SetupVideoWindow())
                    return false;

#if DEBUG
                DsROT.AddGraphToRot(graphBuilder, out rotCookie);		// graphBuilder capGraph
#endif

                hr = mediaCtrl.Run();
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                bool hasTuner = DsUtils.ShowTunerPinDialog(capGraph, capFilter, this.Handle);
                toolBarBtnTune.Enabled = hasTuner;

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary> make the video preview window to show in videoPanel. </summary>
        bool SetupVideoWindow()
        {
            int hr;
            try
            {
                // Set the video window to be a child of the main window
                hr = videoWin.put_Owner(videoPanel.Handle);
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                // Set video window style
                hr = videoWin.put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                // Use helper function to position video window in client rect of owner window
                ResizeVideoWindow();

                // Make the video window visible, now that it is properly positioned
                hr = videoWin.put_Visible(DsHlp.OATRUE);
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                hr = mediaEvt.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero);
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary> build the capture graph for grabber. </summary>
        bool SetupGraph()
        {
            int hr;
            try
            {
                hr = capGraph.SetFiltergraph(graphBuilder);
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                hr = graphBuilder.AddFilter(capFilter, "Ds.NET Video Capture Device");
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                DsUtils.ShowCapPinDialog(capGraph, capFilter, this.Handle);

                AMMediaType media = new AMMediaType();
                media.majorType = MediaType.Video;
                media.subType = MediaSubType.RGB24;
                media.formatType = FormatType.VideoInfo;		// ???
                hr = sampGrabber.SetMediaType(media);
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                hr = graphBuilder.AddFilter(baseGrabFlt, "Ds.NET Grabber");
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                Guid cat = PinCategory.Preview;
                Guid med = MediaType.Video;
                hr = capGraph.RenderStream(ref cat, ref med, capFilter, null, null); // baseGrabFlt 
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                cat = PinCategory.Capture;
                med = MediaType.Video;
                hr = capGraph.RenderStream(ref cat, ref med, capFilter, null, baseGrabFlt); // baseGrabFlt 
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                media = new AMMediaType();
                hr = sampGrabber.GetConnectedMediaType(media);
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);
                if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero))
                    throw new NotSupportedException("Unknown Grabber Media Format");

                videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader));
                Marshal.FreeCoTaskMem(media.formatPtr); media.formatPtr = IntPtr.Zero;

                hr = sampGrabber.SetBufferSamples(false);
                if (hr == 0)
                    hr = sampGrabber.SetOneShot(false);
                if (hr == 0)
                    hr = sampGrabber.SetCallback(null, 0);
                if (hr < 0)
                    Marshal.ThrowExceptionForHR(hr);

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary> create the used COM components and get the interfaces. </summary>
        bool GetInterfaces()
        {
            Type comType = null;
            object comObj = null;
            try
            {
                comType = Type.GetTypeFromCLSID(Clsid.FilterGraph);
                if (comType == null)
                    throw new NotImplementedException(@"DirectShow FilterGraph not installed/registered!");
                comObj = Activator.CreateInstance(comType);
                graphBuilder = (IGraphBuilder)comObj; comObj = null;

                Guid clsid = Clsid.CaptureGraphBuilder2;
                Guid riid = typeof(ICaptureGraphBuilder2).GUID;
                comObj = DsBugWO.CreateDsInstance(ref clsid, ref riid);
                capGraph = (ICaptureGraphBuilder2)comObj; comObj = null;

                comType = Type.GetTypeFromCLSID(Clsid.SampleGrabber);
                if (comType == null)
                    throw new NotImplementedException(@"DirectShow SampleGrabber not installed/registered!");
                comObj = Activator.CreateInstance(comType);
                sampGrabber = (ISampleGrabber)comObj; comObj = null;

                mediaCtrl = (IMediaControl)graphBuilder;
                videoWin = (IVideoWindow)graphBuilder;
                mediaEvt = (IMediaEventEx)graphBuilder;
                baseGrabFlt = (IBaseFilter)sampGrabber;
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (comObj != null)
                    Marshal.ReleaseComObject(comObj); comObj = null;
            }
        }

        /// <summary> create the user selected capture device. </summary>
        bool CreateCaptureDevice(UCOMIMoniker mon)
        {
            object capObj = null;
            try
            {
                Guid gbf = typeof(IBaseFilter).GUID;
                mon.BindToObject(null, null, ref gbf, out capObj);
                capFilter = (IBaseFilter)capObj; capObj = null;
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (capObj != null)
                    Marshal.ReleaseComObject(capObj); capObj = null;
            }

        }

        /// <summary> do cleanup and release DirectShow. </summary>
        void CloseInterfaces()
        {
            int hr;
            try
            {
#if DEBUG
                if (rotCookie != 0)
                    DsROT.RemoveGraphFromRot(ref rotCookie);
#endif

                if (mediaCtrl != null)
                {
                    hr = mediaCtrl.Stop();
                    mediaCtrl = null;
                }

                if (mediaEvt != null)
                {
                    hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
                    mediaEvt = null;
                }

                if (videoWin != null)
                {
                    hr = videoWin.put_Visible(DsHlp.OAFALSE);
                    hr = videoWin.put_Owner(IntPtr.Zero);
                    videoWin = null;
                }

                baseGrabFlt = null;
                if (sampGrabber != null)
                    Marshal.ReleaseComObject(sampGrabber); sampGrabber = null;

                if (capGraph != null)
                    Marshal.ReleaseComObject(capGraph); capGraph = null;

                if (graphBuilder != null)
                    Marshal.ReleaseComObject(graphBuilder); graphBuilder = null;

                if (capFilter != null)
                    Marshal.ReleaseComObject(capFilter); capFilter = null;

                if (capDevices != null)
                {
                    foreach (DsDevice d in capDevices)
                        d.Dispose();
                    capDevices = null;
                }
            }
            catch
            { }
        }

        /// <summary> resize preview video window to fill client area. </summary>
        void ResizeVideoWindow()
        {
            if (videoWin != null)
            {
                Rectangle rc = videoPanel.ClientRectangle;
                videoWin.SetWindowPosition(0, 0, rc.Right, rc.Bottom);
            }
        }

        /// <summary> override window fn to handle graph events. </summary>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_GRAPHNOTIFY)
            {
                if (mediaEvt != null)
                    OnGraphNotify();
                return;
            }
            base.WndProc(ref m);
        }

        /// <summary> graph event (WM_GRAPHNOTIFY) handler. </summary>
        void OnGraphNotify()
        {
            DsEvCode code;
            int p1, p2, hr = 0;
            do
            {
                hr = mediaEvt.GetEvent(out code, out p1, out p2, 0);
                if (hr < 0)
                    break;
                hr = mediaEvt.FreeEventParams(code, p1, p2);
            }
            while (hr == 0);
        }

        /// <summary> sample callback, NOT USED. </summary>
        int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
        {
            Trace.WriteLine("!!CB: ISampleGrabberCB.SampleCB");
            return 0;
        }

        /// <summary> buffer callback, COULD BE FROM FOREIGN THREAD. </summary>
        int ISampleGrabberCB.BufferCB(double SampleTime, IntPtr pBuffer, int BufferLen)
        {
            if (captured || (savedArray == null))
            {
                Trace.WriteLine("!!CB: ISampleGrabberCB.BufferCB");
                return 0;
            }

            captured = true;
            bufferedSize = BufferLen;
            Trace.WriteLine("!!CB: ISampleGrabberCB.BufferCB  !GRAB! size = " + BufferLen.ToString());
            if ((pBuffer != IntPtr.Zero) && (BufferLen > 1000) && (BufferLen <= savedArray.Length))
                Marshal.Copy(pBuffer, savedArray, 0, BufferLen);
            else
                Trace.WriteLine("    !!!GRAB! failed ");
            this.BeginInvoke(new CaptureDone(this.OnCaptureDone));
            return 0;
        }

        /// <summary> event when callback has finished (ISampleGrabberCB.BufferCB). </summary>
        private delegate void CaptureDone();

        private void timer1_Tick(object sender, System.EventArgs e)
        {
            System.Windows.Forms.ToolBarButtonClickEventArgs ee = new ToolBarButtonClickEventArgs(toolBarBtnGrab);
            toolBar_ButtonClick(toolBarBtnGrab, ee);
        }

        private void btnStart_Click(object sender, System.EventArgs e)
        {
            if (this.CNP == "")
            {
                MessageBox.Show("Selectati un pacient inainte.",
                                "Eroare",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            btnStart.Enabled = false;
            btnStop.Enabled = true;
            timer1.Enabled = true;
            startDate = DateTime.Now;
            hasStarted = true;
        }

        private void trckBarSaveValue_ValueChanged(object sender, System.EventArgs e)
        {
            cPercent = trckBarSaveValue.Value;
            lblSavePercent.Text = cPercent + "%";
        }

        private void btnStop_Click(object sender, System.EventArgs e)
        {
            btnStart.Enabled = true;
            btnStop.Enabled = false;
            timer1.Enabled = false;
            firstRun = true;
            stopDate = DateTime.Now;
        }

        private void trckBarTimer_ValueChanged(object sender, System.EventArgs e)
        {
            timer1.Interval = trckBarTimer.Value;
            lblTimerValue.Text = trckBarTimer.Value.ToString();
        }

        private void btSelectarePacient_Click(object sender, EventArgs e)
        {
            VizualizarePacienti vp = new VizualizarePacienti(limba);
            vp.ShowDialog();

            if (vp.CNP != null && !vp.CNP.Equals(string.Empty))
            {
                this.CNP = vp.CNP;
                lbCNP.Text = this.CNP;
            }

            vp.Dispose();
            vp = null;
        }

        private void btSalvare_Click(object sender, EventArgs e)
        {
            if (btnStart.Enabled == false)
                btnStop_Click(null, null);

            if (!hasStarted)
                return;

            // Upload imagini pe server
            UploadIm ui = new UploadIm(limba, filePath, FTPIp, FTPUser, FTPParola, FTPPort);
            ui.ShowDialog();

            if (!ui.success)
            {
                ui.Dispose();
                return;
            }
            ui.Dispose();

            // Salvare in BD
            PersistenceManager pm = PersistenceManager.Instance;
            ImaginiWebCam iwc = new ImaginiWebCam();

            iwc.IdPacient = CNP;
            iwc.Locatie = filePath;
            iwc.DataInceput = startDate;
            iwc.DataSfarsit = stopDate;

            pm.Save(iwc);

        }

    }

    internal enum PlayState
    {
        Init, Stopped, Paused, Running
    }

}
